import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/widget/common_attachment.dart';
import 'package:yuan_hang_app/widget/label_item.dart';
import 'package:yuan_hang_app/widget/photo_view.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

class ActivityDetailPage extends StatefulWidget {
  int activityId;
  String activityTypeName;

  ActivityDetailPage(
      {super.key, required this.activityId, required this.activityTypeName});

  @override
  BaseState<ActivityDetailPage> createState() => _ActivityDetailPageState();
}

class _ActivityDetailPageState extends BaseState<ActivityDetailPage> {
  List picList = [
    "https://files.yuanhangqiche.com/source/upload/55a288a4130c474bb8b6651b50a09291.jpg",
    "https://files.yuanhangqiche.com/source/upload/b512e9a7ca1d4092bdb7b60d5c149d6f.jpg",
    "https://files.yuanhangqiche.com/source/upload/b512e9a7ca1d4092bdb7b60d5c149d6f.jpg",
    "https://files.yuanhangqiche.com/source/upload/9b01b18078e348a6843c4b3613dc915b.jpg",
    "https://files.yuanhangqiche.com/source/upload/d0bb9bf3439d442e9b0c454bc6e1d74b.jpg",
  ]; //头部 b
  Map detailInfo = {};

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "活动详情",
      child:SingleChildScrollView(
        padding: EdgeInsets.zero,
        child:  Column(
          children: [_cardItem("活动基础信息", _baseInfo())],
        ),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    showLoading();
    HttpUtils()
        .get(
      "${Api.getMarketActivity}?id=${widget.activityId}",
    )
        .then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        detailInfo = data.data;
        detailInfo["modelName"] = getModelNames(detailInfo["modelIds"]);
        detailInfo["activityTypeName"] = widget.activityTypeName;
        setState(() {});
      } else if (data.resultCode == 500) {
        Toast.toast(data.errMsg ?? "");
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Column _baseInfo() {
    return Column(
      children: [
        LabelItem(
          label: "活动编号",
          value: StringUtils.safeGetValue(detailInfo["activityCode"],
              placeHolder: "-"),
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "活动名称",
          value: StringUtils.safeGetValue(detailInfo["activityName"],
              placeHolder: "-"),
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "活动车型",
          value: StringUtils.safeGetValue(detailInfo["modelName"],
              placeHolder: "-"),
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "活动类型",
          value: StringUtils.safeGetValue(detailInfo["activityTypeName"],
              placeHolder: "-"),
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "活动日期",
          value: "${StringUtils.safeGetValue(
            detailInfo["startDate"],
          )}  -  ${StringUtils.safeGetValue(
            detailInfo["endDate"],
          )}",
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "活动时间",
          value: "${StringUtils.safeGetValue(
            detailInfo["startActivityTime"],
          )} - ${StringUtils.safeGetValue(
            detailInfo["endActivityTime"],
          )}",
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "活动备注",
          isEnabled: false,
          isLast: true,
          value:
              StringUtils.safeGetValue(detailInfo["remark"], placeHolder: "-"),
          labelType: LabelType.TEXTAREA,
        ),
      ],
    );
  }

  Container _cardItem(String label, Widget child, {double bottom = 0}) {
    return Container(
      margin: EdgeInsets.only(
          top: 10.px, left: 15.px, right: 15.px, bottom: bottom.px),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(10.px)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 48.px,
            alignment: Alignment.centerLeft,
            // padding: EdgeInsets.only(left: 15.px),
            child: Row(
              children: [
                WLine(
                    width: 4.px,
                    height: 16.px,
                    color: WColors.primaryColor,
                    marginRight: 15.px),
                WText(
                  label,
                  style: TextStyle(
                      fontSize: WDimens.tsLarge,
                      color: WColors.mainTextColor,
                      fontWeight: FontWeight.bold),
                )
              ],
            ),
          ),
          WLine(
            height: 1.px,
          ),
          child
        ],
      ),
    );
  }

  Widget _getPicWidget() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            WText(
              "附件",
              style: TextStyle(
                  color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
            ),
            GridView.builder(
              shrinkWrap: true,
              padding: EdgeInsets.only(bottom: 10.px, top: 5.px),
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  mainAxisSpacing: 10.px,
                  crossAxisCount: 4,
                  crossAxisSpacing: 10.px,
                  childAspectRatio: 1),
              itemBuilder: _picItemBuilder,
              itemCount: picList.length,
            )
          ],
        ));
  }

  Widget _picItemBuilder(context, index) {
    return GestureDetector(
      onTap: () {
        RouteHelper.pushWidget(
            context, PhotoView(imgs: picList, currentIndex: index));
      },
      child: FadeInImage(
          placeholder: const AssetImage("images/banner.png"),
          imageErrorBuilder: (cxt, ob, s) => Image.asset("images/banner.png",
              height: (SizeUtils.screenW() / 4).px),
          height: (SizeUtils.screenW() / 4).px,
          fit: BoxFit.cover,
          image: NetworkImage(picList[index])),
    );
  }

  String getModelNames(modelIds) {
    String name = "";
    List<String> ids = modelIds.toString().split(",");
    for (Map model in WConstant.modelList) {
      for (String id in ids) {
        if (model["id"].toString() == id) {
          name += model["label"] + ",";
          break;
        }
      }
    }
    if (name.isNotEmpty) {
      name = name.substring(0, name.length - 1);
    } else {
      name = "";
    }
    return name;
  }
}
